package top.lunarye.handler.pending;

import org.springframework.stereotype.Component;
import top.lunarye.handler.config.HandlerThreadPoolConfig;
import top.lunarye.handler.utils.GroupIdMappingUtils;
import top.lunarye.support.utils.ThreadPoolUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * 存储每种消息类型与TaskPending的关系
 * @author lunar
 * @since 2022-07-18
 */
@Component
public class TaskPendingHolder {

    @Resource
    private ThreadPoolUtils threadPoolUtils;

    private final Map<String, ExecutorService> taskPendingHolder = new HashMap<>(32);

    // 得到所有的 groupId
    private static List<String> groudIds = GroupIdMappingUtils.getAllGroupIds();

    /**
     * 为每个渠道的每种消息类型都初始化一个线程池
     * @PostConstruct 会在服务器加载Servlet的时候运行，并且只会被服务器执行一次
     * 执行的顺序为：Constructor(构造方法) -> @Resource(依赖注入) -> @PostConstruct
     */
    @PostConstruct
    public void init() {
        for (var groupId : groudIds) {
            var executor = HandlerThreadPoolConfig.getExecutor(groupId);
            threadPoolUtils.register(executor);

            taskPendingHolder.put(groupId, executor);
        }
    }

    /**
     * 依据传入的groupId得到对应的线程池
     * @param groupId
     * @return
     */
    public ExecutorService route(String groupId) {
        return taskPendingHolder.get(groupId);
    }
}
